package com.motu.monstercity.server.game.logichandler;

import com.motu.monstercity.module.common.network.RequestParam;
import com.motu.monstercity.protocol.Common.PBUserData;
import com.motu.monstercity.protocol.Common.PBUserSecretary;
import com.motu.monstercity.protocol.CsGameSecretary;
import com.motu.monstercity.protocol.CsGameSecretary.CSGameSecretaryPotentialSkillLevelUpRequest;
import com.motu.monstercity.protocol.CsGameSecretary.CSGameSecretaryPotentialSkillLevelUpResponse;
import com.motu.monstercity.protocol.CsGameSecretary.CSGameSecretaryPotentialSkillListRequest;
import com.motu.monstercity.protocol.CsGameSecretary.CSGameSecretaryPotentialSkillListResponse;
import com.motu.monstercity.server.game.base.AllParam;
import com.motu.monstercity.server.game.base.CommonUtils;
import com.motu.monstercity.server.game.base.ProtoDataUtils;
import com.motu.monstercity.server.game.commondata.bag.BagConstant;
import com.motu.monstercity.server.game.commondata.bag.Item;
import com.motu.monstercity.server.game.commondata.bag.ItemId;
import com.motu.monstercity.server.game.commondata.maintask.MainTaskConstant;
import com.motu.monstercity.server.game.commondata.partner.PartnerConstant;
import com.motu.monstercity.server.game.commondata.secretary.SecretaryPotentialSkill;
import com.motu.monstercity.server.game.commondata.skill.Skill;
import com.motu.monstercity.server.game.commondata.secretary.SecretaryIdentity;
import com.motu.monstercity.server.game.commondata.secretary.SecretaryMain;
import com.motu.monstercity.server.game.commondata.suit.Suit;
import com.motu.monstercity.server.game.log.LogType;
import com.motu.monstercity.server.game.logic.*;
import com.motu.monstercity.server.game.userdata.*;
import com.motu.vertx.module.utility.toolset.ErrorWord;
import com.motu.vertx.module.utility.toolset.Tool;
import io.vertx.core.json.JsonArray;

import java.util.List;

public class SecretaryHandler {

    // CMD_GAME_SECRETARY_REFRESH = 70801; // 秘书信息重载（更新体力）
    public static Object CMD_GAME_SECRETARY_REFRESH(RequestParam clientParam) throws Exception {
        long userId = clientParam.getUserId();
        CsGameSecretary.CSGameSecretaryRefreshRequest request = CsGameSecretary.CSGameSecretaryRefreshRequest.parseFrom(clientParam.getData());
        CsGameSecretary.CSGameSecretaryRefreshResponse.Builder response = CsGameSecretary.CSGameSecretaryRefreshResponse.newBuilder();
        PBUserData.Builder pbUserData = response.getUserBuilder();
        UserInfo userInfo = GameUser.getUserInfo(userId);
        UserPower userPower = GameUser.getUserPower(userId);
        List<UserSecretary> userSecretaryList = SecretaryManager.getUserSecretaries(userId);
        for (UserSecretary userSecretary : userSecretaryList) {
            ProtoDataUtils.updatePBUserData(pbUserData, userSecretary);
        }
        return response;
    }

    // CMD_GAME_SECRETARY_IDENTITY_SKILL_LEVEL_UP = 70803; // 秘书基因技能升级
    public static Object CMD_GAME_SECRETARY_IDENTITY_SKILL_LEVEL_UP(RequestParam clientParam) throws Exception {
        CsGameSecretary.CSGameSecretaryIdentitySkillLevelUpRequest request = CsGameSecretary.CSGameSecretaryIdentitySkillLevelUpRequest.parseFrom(clientParam.getData());
        CsGameSecretary.CSGameSecretaryIdentitySkillLevelUpResponse.Builder response = CsGameSecretary.CSGameSecretaryIdentitySkillLevelUpResponse.newBuilder();

        long userId = clientParam.getUserId();
        int secretaryId = request.getSecretaryId();

        UserSecretary userSecretary = SecretaryManager.getUserSecretary(userId, secretaryId);
        if (null == userSecretary) {
            return ErrorWord.NOT_DATA;
        }
        int curLevel = userSecretary.getIdentitySkillLevel();
        int nextLevel = curLevel + 1;
        SecretaryIdentity curConfig = SecretaryManager.getSecretaryIdentity(curLevel);
        SecretaryIdentity nextConfig = SecretaryManager.getSecretaryIdentity(nextLevel);
        if (curConfig == null || nextConfig == null) {
            return ErrorWord.ALREADY_MAX;
        }

        if (userSecretary.getFavorite() < curConfig.getNeedFavorite() || userSecretary.getCharm() < curConfig.getNeedCharm()) {
            return ErrorWord.INVALID_OPERATION;
        }
        long secretaryCount = SecretaryManager.getUserSecretaryCount(userId);
        if (secretaryCount < curConfig.getNeedBeautyNum()) {
            return ErrorWord.ITEM_LACK;
        }

        //  执行逻辑
        PBUserData.Builder pbUserData = response.getUserBuilder();
        UserInfo userInfo = GameUser.getUserInfo(userId);
        UserPower userPower = GameUser.getUserPower(userId);

        userSecretary.putIdentitySkillLevel(pbUserData, userInfo, userPower, nextLevel);
        userSecretary.update();
        ProtoDataUtils.updatePBUserData(pbUserData, userSecretary);

        MainTaskManager.addTaskProgress(pbUserData, userInfo, MainTaskConstant.TASK_TYPE_145, 1);
        RankActManager.addTaskProgress(pbUserData, userInfo, MainTaskConstant.TASK_TYPE_145, 1);
        return response;
    }

    // CMD_GAME_SECRETARY_PATRONS_SKILL_LEVEL_UP = 70804; // 秘书羁绊技能升级
    public static Object CMD_GAME_SECRETARY_PATRONS_SKILL_LEVEL_UP(RequestParam clientParam) throws Exception {
        CsGameSecretary.CSGameSecretaryPatronsSkillLevelUpRequest request = CsGameSecretary.CSGameSecretaryPatronsSkillLevelUpRequest.parseFrom(clientParam.getData());
        CsGameSecretary.CSGameSecretaryPatronsSkillLevelUpResponse.Builder response = CsGameSecretary.CSGameSecretaryPatronsSkillLevelUpResponse.newBuilder();

        long userId = clientParam.getUserId();
        int secretaryId = request.getSecretaryId();
        int index = request.getIndex();

        if (index > AllParam.SECRETRAY_PATRONS_SKILL.length) {
            return ErrorWord.BAD_PARAM;
        }

        int skillId = AllParam.SECRETRAY_PATRONS_SKILL[index];
        Skill skill = SkillManager.getSkill(skillId);
        if (skill == null) {
            return ErrorWord.NOT_DATA_1;
        }

        UserSecretary userSecretary = SecretaryManager.getUserSecretary(userId, secretaryId);
        if (null == userSecretary) {
            return ErrorWord.NOT_DATA;
        }

        JsonArray skillLevelList = userSecretary.getSkillPatronLevelArray();
        int curLevel = skillLevelList.getInteger(index);// 羁绊技能当前的等级
        int nextLevel = curLevel + 1;

        if (skill.getMaxLevel() > 0 && skill.getMaxLevel() < nextLevel) {
            return ErrorWord.ALREADY_MAX;
        }

        UserInfo userInfo = GameUser.getUserInfo(userId);
        List<RewardItem> rewardItems = skill.takeLevelUpItems(curLevel);// 消耗的道具数量
        rewardItems.forEach(item -> item.setEntity(userSecretary));
        if (!BagManager.checkNeedItemNum(userInfo, rewardItems, userSecretary)) {
            return ErrorWord.ITEM_LACK;// 道具不足
        }

        // 执行逻辑
        PBUserData.Builder pbUserData = response.getUserBuilder();
        UserPower userPower = GameUser.getUserPower(userId);
        RewardManager.subReward(userInfo, rewardItems, pbUserData, LogType.SECRETARY_PATRONS_SKILL_LEVEL_UP, secretaryId);
        skillLevelList.set(index, nextLevel);
        userSecretary.putSkillPatronLevel(skillLevelList.toString());
        userSecretary.update();
        ProtoDataUtils.updatePBUserData(pbUserData, userSecretary);
        long addPower = SecretaryManager.countPatronLevelUp(pbUserData, userInfo, userPower, userSecretary, skill, nextLevel);// 升级秘书的羁绊技能，只会增加羁绊干员的战力百分比，或是战力固定值
        if (addPower > 0) {
            long newPower = userPower.getPower() + addPower;
            userPower.handlePowerChange(pbUserData, userInfo, newPower);// 玩家的战力发生变化，基础战力变化，或是加成有变化，全量更新总战力,城市收益有变化也要下发
        }

        MainTaskManager.addTaskProgress(pbUserData, userInfo, MainTaskConstant.TASK_TYPE_191, 1);// 更新主线任务,成就,日常任务的进度
        RankActManager.addTaskProgress(pbUserData, userInfo, MainTaskConstant.TASK_TYPE_191, 1);

        return response;
    }

    // CMD_GAME_SECRETARY_SEND_GIFT = 70805; // 送秘书礼物
    public static Object CMD_GAME_SECRETARY_SEND_GIFT(RequestParam clientParam) throws Exception {
        long userId = clientParam.getUserId();
        UserInfo userInfo = GameUser.getUserInfo(userId);
        CsGameSecretary.CSGameSecretarySendGiftRequest request = CsGameSecretary.CSGameSecretarySendGiftRequest.parseFrom(clientParam.getData());
        int secId = request.getSecretaryId();
        UserSecretary userSecretary = SecretaryManager.getUserSecretary(userId, secId);
        if (null == userSecretary) {
            return ErrorWord.NOT_DATA;
        }
        int itemId = request.getItemId();
        int num = request.getNum();
        if (BagManager.getUserItemNum(userInfo, itemId) < num) {
            return ErrorWord.ITEM_LACK;// 道具不足
        }
        Item item = BagManager.getItem(itemId);
        if (item == null) {
            return ErrorWord.NOT_DATA_1; // 未配置道具
        }
        if (item.getUseType() != Item.USE_TYPE_SECRETARY) {
            return ErrorWord.INVALID_OPERATION; // 不是秘书道具
        }
        CsGameSecretary.CSGameSecretarySendGiftResponse.Builder response = CsGameSecretary.CSGameSecretarySendGiftResponse.newBuilder();
        PBUserData.Builder userData = response.getUserBuilder();
        UserPower userPower = GameUser.getUserPower(userId);
        UserAffair userAffair = GameUser.getUserAffair(userId);
        RewardManager.subReward(userInfo, itemId, num, userData, LogType.SECRETARY_SEND_GIFT);
        int addUnit = Tool.stringToInt(item.getParam2());
        if (item.getEffectType() == BagConstant.ITEM_EFFECT_TYPE_3) {
            userSecretary.addFavorite(userData, userInfo, userPower, userAffair, addUnit * num);
        } else if (item.getEffectType() == BagConstant.ITEM_EFFECT_TYPE_4) {
            int addCharm = addUnit * num;
            userSecretary.addCharm(userData, userInfo, addCharm);
        }
        userSecretary.update();
        ProtoDataUtils.updatePBUserData(userData, userSecretary);
        MainTaskManager.addTaskProgress(userData, userInfo, MainTaskConstant.TASK_TYPE_31, num);// 更新主线任务,成就,日常任务的进度
        MainTaskManager.addTaskProgress(userData, userInfo, MainTaskConstant.TASK_TYPE_116, num);// 更新主线任务,成就,日常任务的进度
        RankActManager.addTaskProgress(userData, userInfo, MainTaskConstant.TASK_TYPE_31, num);
        RankActManager.addTaskProgress(userData, userInfo, MainTaskConstant.TASK_TYPE_116, num);
        return response;
    }

    // CMD_GAME_SECRETARY_DRESS_SUIT = 70806; // 秘书穿戴服饰
    public static Object CMD_GAME_SECRETARY_DRESS_SUIT(RequestParam clientParam) throws Exception {
        long userId = clientParam.getUserId();
//        UserInfo userInfo = GameUser.getUserInfo(userId);
        CsGameSecretary.CSGameSecretaryDressSuitRequest request = CsGameSecretary.CSGameSecretaryDressSuitRequest.parseFrom(clientParam.getData());
        int secId = request.getSecretaryId();
        UserSecretary userSecretary = SecretaryManager.getUserSecretary(userId, secId);
        if (null == userSecretary) {
            return ErrorWord.NOT_DATA;
        }
        int suitId = request.getSuitId();
        SecretaryMain secretaryMain = SecretaryManager.getSecretaryMain(secId);
        if (null == secretaryMain) {
            return ErrorWord.NOT_DATA;
        }
        if (userSecretary.getSuitId() == suitId) {
            return ErrorWord.REPEATED_OPERATION; // 已经穿戴上这件服装
        }
        Suit suit = SuitManager.getSuit(suitId);
        if (null == suit) {
            return ErrorWord.NOT_DATA_1;
        }
        if (suit.getOwnerId() != userSecretary.getSecretaryId()) {
            return ErrorWord.INVALID_OPERATION;
        }
        UserSuit userSuit = SuitManager.getUserSuit(userId, suitId);
        if (null == userSuit) {
            return ErrorWord.NOT_DATA_2;
        }
        userSecretary.putSuitId(suitId);
        userSecretary.update();

        CsGameSecretary.CSGameSecretaryDressSuitResponse.Builder response = CsGameSecretary.CSGameSecretaryDressSuitResponse.newBuilder();
        PBUserData.Builder userData = response.getUserBuilder();
        ProtoDataUtils.updatePBUserData(userData, userSecretary);
        return response;
    }

    // CMD_GAME_SECRETARY_POTENTIAL_SKILL_LEVEL_UP = 70807; // 秘书经营技能升级
    public static Object CMD_GAME_SECRETARY_POTENTIAL_SKILL_LEVEL_UP(RequestParam clientParam) throws Exception {
        CSGameSecretaryPotentialSkillLevelUpRequest request = CSGameSecretaryPotentialSkillLevelUpRequest.parseFrom(clientParam.getData());
        CSGameSecretaryPotentialSkillLevelUpResponse.Builder response = CSGameSecretaryPotentialSkillLevelUpResponse.newBuilder();
        long userId = clientParam.getUserId();

        int type = request.getType();
        int secretaryId = request.getSecretaryId();
        int skillId = request.getSkillId();

        SecretaryPotentialSkill skill = SecretaryManager.getSecretaryPotentialSkill(skillId);
        if (skill == null) {
            return ErrorWord.NOT_DATA;
        }

        UserSecretary userSecretary = SecretaryManager.getUserSecretary(userId, secretaryId);
        if (userSecretary == null) {
            return ErrorWord.WRONG_STATUS;// 未解锁该秘书
        }

        UserSecretaryBusiness userSecretaryBusiness = SecretaryManager.getUserSecretaryBusiness(userId, secretaryId, skillId);
        if (userSecretaryBusiness == null) {
            return ErrorWord.WRONG_STATUS;// 未解锁该技能
        }

        UserInfo userInfo = GameUser.getUserInfo(userId);
        int itemId;
        int num;
        int[] weight;
        if (type == 1) { // 金币升级
            itemId = ItemId.GOLD;
            num = (int) (0.1 * Math.pow(userSecretaryBusiness.getLevelCount(), 4) + 8); // 0.1*x^4+8
            weight = AllParam.SECRETRAY_SKILL_NORMAL_MODIFY_PARAM;
        } else {
            itemId = ItemId.LUCKY_COIN;
            num = 1;
            weight = AllParam.SECRETRAY_SKILL_CUSTOM_MODIFY_PARAM;
        }
        if (BagManager.getUserItemNum(userInfo, itemId) < num) {
            return ErrorWord.ITEM_LACK; // 道具不足
        }

        // 执行逻辑
        PBUserData.Builder pbUserData = response.getUserBuilder();
        int randIndex = CommonUtils.getRandom(weight);// 根据权重数值，返回随机结果 如策划配置0;10000;15000;18000 这样的权重数组，随机到15000，则返回结果是3
        int value = randIndex * 100;// 300表示加成3% 放大到W倍
        UserPower userPower = GameUser.getUserPower(userId);
        RewardManager.subReward(userInfo, itemId, num, pbUserData, LogType.SECRETARY_POTENTIAL_SKILL_REFRESH, userSecretaryBusiness.getValue() + "_" + value);
        userSecretaryBusiness.addLevelCount(1);
        if (userSecretaryBusiness.getValue() < value) {
            userSecretaryBusiness.addValue(pbUserData, userInfo, userPower, userSecretary, skill.getCharacterType(), value - userSecretaryBusiness.getValue());
            userSecretary.update();
            userPower.update();
            List<UserBuild> buildList = userPower.takeUserBuildList(skill.getCharacterType());
            BuildManager.batchUpdateBuildEarn(pbUserData, userInfo, userPower, buildList);// 更新这个性格的商业建筑的加成，并更新到userpower下发给客户端
        }
        userSecretaryBusiness.update();
        ProtoDataUtils.updatePBUserData(pbUserData, userSecretaryBusiness);
        response.setValue(value);

        MainTaskManager.addTaskProgress(pbUserData, userInfo, MainTaskConstant.TASK_TYPE_26, 1, secretaryId);// 更新主线任务,成就,日常任务的进度
        MainTaskManager.addTaskProgress(pbUserData, userInfo, MainTaskConstant.TASK_TYPE_136, 1);// 更新主线任务,成就,日常任务的进度
        RankActManager.addTaskProgress(pbUserData, userInfo, MainTaskConstant.TASK_TYPE_26, 1, secretaryId);
        RankActManager.addTaskProgress(pbUserData, userInfo, MainTaskConstant.TASK_TYPE_136, 1);
        return response;
    }


    // CMD_GAME_SECRETARY_POTENTIAL_SKILL_LIST = 70808; // 获得某个秘书的所有经营技能
    public static Object CMD_GAME_SECRETARY_POTENTIAL_SKILL_LIST(RequestParam clientParam) throws Exception {
        CSGameSecretaryPotentialSkillListRequest request = CsGameSecretary.CSGameSecretaryPotentialSkillListRequest.parseFrom(clientParam.getData());
        CSGameSecretaryPotentialSkillListResponse.Builder response = CSGameSecretaryPotentialSkillListResponse.newBuilder();
        long userId = clientParam.getUserId();

        int secrId = request.getSecretaryId();
        PBUserData.Builder pbUserData = response.getUserBuilder();
        UserSecretary userSecretary = SecretaryManager.getUserSecretary(userId, secrId);
        userSecretary.reCountBusiness(pbUserData);
        userSecretary.update();// 重算经营技能的加成值
        return response;
    }
}
